<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Operation\Service\Common;

use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Laminas\I18n\Translator\Translator;
use Sales\Entity\OrderDiscountRecord;

class Discount
{
    public static function discountCalculation($goodsCart, $data, EntityManager $entityManager, Translator $translator)
    {
        $discountRule = Common::readConfigFile('discountRule');

        $discountCost = 0;
        $discountId   = 0;
        //如无规则，则无优惠
        if (empty($discountRule)) return 0;
        foreach ($discountRule as $ruleKey => $ruleValue) {
            if (!Common::checkTime($ruleValue['discountStartTime'], $ruleValue['discountEndTime'])) continue;
            if (!Common::checkUser($data['userGroupId'], $ruleValue['discountUserType'], $ruleValue['discountUserGroup'])) continue;

            if ($ruleValue['userBuyFrequency'] > 0) {//判断是否有频次限制
                $userBuyFrequencyNum = $entityManager->getRepository(OrderDiscountRecord::class)->count(['userId' => $data['userId'], 'discountType' => 'discount', 'id' => $ruleKey]);
                if ($userBuyFrequencyNum >= $ruleValue['userBuyFrequency']) continue;
            }

            $costTotal = self::cartCostTotal($goodsCart, $ruleValue);

            if ($costTotal >= $ruleValue['goodsBuyAmount']) {
                if ($ruleValue['goodsBuyType'] == 1) {//满X元
                    //discountMode 1 元，2 百分比
                    $price = $ruleValue['discountMode'] == 1 ? $ruleValue['buyDiscount'] : ($costTotal * $ruleValue['buyDiscount'] / 100);
                } else {//每X元
                    //discountMode 1 元，2 百分比
                    $price = ($ruleValue['discountMode'] == 1 ? $ruleValue['buyDiscount'] : ($ruleValue['goodsBuyAmount'] * $ruleValue['buyDiscount'] / 100)) * floor($costTotal/$ruleValue['goodsBuyAmount']);
                }

                if ($discountCost == 0 || ($discountCost > 0 && $discountCost < $price)) {
                    $discountCost   = $price;
                    $discountId     = $ruleKey;
                }
            }
        }

        return ['discountCost' => $discountCost, 'discountTitle' => $translator->translate('优惠立减'), 'discountType' => 'discount', 'discountId' => $discountId];
    }

    /**
     * 获取商品详情需要显示的优惠促销
     * @param $data
     * @param Translator $translator
     * @return array
     */
    public static function goodsDiscount($data, Translator $translator)
    {
        $discountArray= [];
        $discountRule = Common::readConfigFile('discountRule');
        if (empty($discountRule)) return $discountArray;

        foreach ($discountRule as $ruleKey => $ruleValue) {
            if (!Common::checkTime($ruleValue['discountStartTime'], $ruleValue['discountEndTime'])) continue;
            if (!Common::checkUser($data['userGroupId'], $ruleValue['discountUserType'], $ruleValue['discountUserGroup'])) continue;
            if (!Common::checkGoods($data['classId'], $ruleValue['discountGoodsType'], $ruleValue['discountGoodsBody'], $data['brandId'])) continue;

            $discountArray[] = [
                'tag'   => $translator->translate('促销'),
                'title' => $ruleValue['discountRuleTitle']
            ];
        }

        return $discountArray;
    }

    /**
     * 购物车过滤符合条件的商品，并计算总金额
     * @param $goodsCart
     * @param $rule
     * @return float|int
     */
    private static function cartCostTotal($goodsCart, $rule)
    {
        $costTotal = 0;
        foreach ($goodsCart as $goodsValue) {
            if (Common::checkGoods($goodsValue['classId'], $rule['discountGoodsType'], $rule['discountGoodsBody'], $goodsValue['brandId'])) {
                $costTotal = $costTotal + $goodsValue['goodsAmount'];
            }
        }

        return $costTotal;
    }
}